package me.green.ui;

import me.green.bean.User;
import me.green.dao.UserDao;
import me.green.ui.component.JImagePanel;
import me.green.ui.global.UIResources;
import me.green.ui.global.UIStyle;
import me.green.ui.global.i18n.UIText;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;

/**
 * 登录窗口
 *
 * @author green
 */
public class LoginFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel panelContent = null;

    private JTextField txtUserName = null;
    private JPasswordField txtPwd = null;

    private JLabel labUserName = null;
    private JLabel labPwd = null;

    private JButton btnLogin = null;
    private JButton btnExit = null;

    private final int WINDOW_WIDTH = 650;
    private final int WINDOW_HEIGHT = 495;
    private final int INPUT_WIDTH = UIStyle.INPUT_WIDTH;
    private final int INPUT_HEIGHT = UIStyle.INPUT_HEIGHT;

    /**
     * This method initializes txtUserName
     *
     * @return javax.swing.JTextField
     */
    private JTextField getTxtUserName() {
        if (txtUserName == null) {
            txtUserName = new JTextField();
            txtUserName.setText("");
            txtUserName.setFont(UIStyle.defaultFont());
            // 设置文本与边框距离（内边距）
            txtUserName.setMargin(new Insets(0, 10, 0, 10));
            txtUserName.setPreferredSize(new Dimension(INPUT_WIDTH, INPUT_HEIGHT));
            txtUserName.requestFocus();
            txtUserName.addKeyListener(new java.awt.event.KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        txtPwd.requestFocus();
                    }
                }
            });
        }
        return txtUserName;
    }

    /**
     * This method initializes txtPwd
     *
     * @return javax.swing.JPasswordField
     */
    private JPasswordField getTxtPwd() {
        if (txtPwd == null) {
            txtPwd = new JPasswordField();
            txtPwd.setText("");
            txtPwd.setPreferredSize(new Dimension(INPUT_WIDTH, INPUT_HEIGHT));
            // 输入字符占位符
            txtPwd.setEchoChar('*');
            txtPwd.setFont(UIStyle.defaultFont());
            txtPwd.setMargin(new Insets(0, 10, 0, 10));
            txtPwd.addKeyListener(new java.awt.event.KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        login();
                    }
                }
            });
        }
        return txtPwd;
    }

    /**
     * This method initializes btnLogin
     *
     * @return javax.swing.JButton
     */
    private JButton getBtnLogin() {
        if (btnLogin == null) {
            btnLogin = new JButton();
            btnLogin.setText(UIStyle.text(UIText.LOGIN));
            btnLogin.setFont(UIStyle.defaultFont());
            btnLogin.setMnemonic(KeyEvent.VK_L);
            btnLogin.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    login();
                }
            });
        }
        return btnLogin;
    }

    /**
     * This method initializes btnExit
     *
     * @return javax.swing.JButton
     */
    private JButton getBtnExit() {
        if (btnExit == null) {
            btnExit = new JButton();
            btnExit.setText(UIStyle.text(UIText.LOGOUT));
            btnExit.setFont(UIStyle.defaultFont());
            btnExit.setMnemonic(KeyEvent.VK_E);
            btnExit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    System.exit(0);
                }
            });
        }
        return btnExit;
    }


    /**
     * This is the default constructor
     */
    public LoginFrame() {
        initialize();
        this.setVisible(true);

        String tip = Env.check();
        if (!tip.isEmpty()) {
            getBtnLogin().setEnabled(false);
            getTxtUserName().setEnabled(false);
            getTxtPwd().setEnabled(false);
            JOptionPane.showMessageDialog(this, tip);
        }
    }

    /**
     * UI初始化
     */
    private void initialize() {
        this.setSize(new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT));
        // 禁止最大化
        this.setResizable(false);
        this.setContentPane(getPanelContent());
        this.setTitle(UIStyle.text(UIText.TITLE));
        this.setIconImage(new ImageIcon(this.getClass().getResource(UIResources.ICON_TRAY)).getImage());
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(this);
    }


    /**
     * 获取主界面容器
     *
     * @return
     */
    private JPanel getPanelContent() {
        if (panelContent == null) {
            panelContent = new JPanel();
            // 头部区域
            ImageIcon iconHeader = new ImageIcon(getClass().getResource(UIResources.BG_HEADER));
            JPanel panelHeader = new JImagePanel(iconHeader);
            panelHeader.setBackground(Color.PINK);
            panelHeader.setPreferredSize(new Dimension(WINDOW_WIDTH, 150));

            // 用户名
            JPanel panelUserName = new JPanel();
            labUserName = new JLabel();
            labUserName.setText("用户名");
            labUserName.setFont(UIStyle.defaultFont());
            labUserName.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
            panelUserName.add(labUserName);
            // 用户名输入框
            panelUserName.add(getTxtUserName());
            panelUserName.setBorder(BorderFactory.createEmptyBorder(25, 0, 5, 0));

            // 密码
            JPanel panelPwd = new JPanel();
            labPwd = new JLabel();
            labPwd.setText("密　码");
            labPwd.setFont(UIStyle.defaultFont());
            labPwd.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
            // 密码框
            panelPwd.add(labPwd);
            panelPwd.add(getTxtPwd());
            panelPwd.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

            // 按钮
            JPanel panelBtn = new JPanel();
            panelBtn.add(getBtnLogin());
            panelBtn.add(getBtnExit());
            panelBtn.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

            // 垂直排列
            Box boxMain = Box.createVerticalBox();
            boxMain.add(panelHeader);
            boxMain.add(panelUserName);
            boxMain.add(panelPwd);
            boxMain.add(panelBtn);
            panelContent.add(boxMain);
        }
        return panelContent;
    }

    /**
     * 登录
     */
    private void login() {
        String userName = txtUserName.getText();
        String password = new String(txtPwd.getPassword());
        User user = new UserDao().login(userName, password);
        if (user != null) {
            LocalCache.setUser(user);
            LoginFrame.this.setVisible(false);
            LoginFrame.this.dispose();
            LocalCache.setFrameApp(new EtnFrame());
        } else {
            JOptionPane.showMessageDialog(LoginFrame.this, UIStyle.text(UIText.ERROR_WRONG_PASSWORD));
            txtPwd.setText("");
            txtPwd.requestFocus();
        }
    }

    static class Env {

        /**
         * 运行环境检查
         *
         * @return
         */
        public static String check() {
            if (!jdk()) {
                return UIStyle.text("tip.env-jdk");
            }
            return "";
        }


        /**
         * JDK版本检查
         *
         * @return
         */
        public static boolean jdk() {
            try {
                // JDK1.6环境支持
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException e) {
                return false;
            }
            return true;
        }

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        UIManager.put("OptionPane.buttonFont", UIStyle.defaultFont());
        UIManager.put("OptionPane.messageFont", UIStyle.defaultFont());
        // macOS风格
//        try {
//            System.setProperty("Quaqua.tabLayoutPolicy", "wrap");
//            UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel");
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (UnsupportedLookAndFeelException e) {
//            e.printStackTrace();
//        }
        new LoginFrame();
    }


}
